<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/22
 * Time: 10:07
 */

namespace app\admin\command;


use app\admin\model\SysAdmin;
use app\common\lib\rongcloud\RongCloud;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

/**
 * 定时任务
 *
 * Class CustomerServiceStatus
 * @package app\admin\command
 */
class CustomerServiceStatus extends Command
{

    protected function configure()
    {
        $this->setName('csStat')->setDescription('遍历检查并保存客服的在线状态');
    }

    protected function execute(Input $input, Output $output)
    {
        $sql = <<<SQL
SELECT a.admin_id,b.realname FROM customer_service a
LEFT JOIN sys_admin b ON a.admin_id = b.id
SQL;
        $list = Db::query($sql);

        $rongUser = RongCloud::getInstance()->User();

        $sql = <<<SQL
UPDATE customer_service SET online=:online WHERE admin_id=:admin_id
SQL;
        $stmt = Db::connect()->getPdo()->prepare($sql);
        foreach ($list as & $item) {
            $admin_id = $item['admin_id'];
            $chatId = SysAdmin::getChatId($admin_id);
            $re = $rongUser->checkOnline($chatId);

            $online = $re['status'] ?? false;
            $stmt->execute([
                'admin_id' => $admin_id,
                'online' => $online,
            ]);
            if ($online) echo "客服{$item['realname']}<{$admin_id}>在线";
            else echo "客服:{$item['realname']}<{$admin_id}>下线";
            echo PHP_EOL;
        }

    }

}